package com.csp.app.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.csp.app.common.Const;
import com.csp.app.entity.Friend;
import com.csp.app.entity.User;
import com.csp.app.mapper.FriendMapper;
import com.csp.app.mapper.UserMapper;
import com.csp.app.service.FriendService;
import com.csp.app.service.RedisService;
import com.csp.app.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendService friendService;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private RedisService redisService;
    @Override
    public User login(User user) {
        return selectOne(new EntityWrapper<>(user));
    }

    @Override
    public User register(User user) {
        Long maxAccount = userMapper.selectMaxAccount();
        Long tempAccount = maxAccount;
        if (tempAccount == null) {
            tempAccount = Const.INIT_ACCOUNT;
        } else {
            tempAccount++;
        }
        user.setUsername(String.valueOf(tempAccount));
        user.setId(tempAccount);
        userMapper.addUser(user);
        return user;
    }

    @Override
    public List<User> searchFriend(User user) {
        String username = user.getUsername();
        user.setUsername(null);
        EntityWrapper<User> wrapper = new EntityWrapper<>(user);
        if (StringUtils.isNotEmpty(username)) {
            wrapper.like("username", "%" + username + "%");
        }
        wrapper.setSqlSelect("id", "avatar", "username", "sign", "sex");
        return selectList(wrapper);
    }

    @Override
    public User addFriend(Friend friend) {
        friendMapper.addFriend(friend.getId(), friend.getFriendId());
        String key = String.format(Const.USER_ID_USER, friend.getFriendId());
        return redisService.getObject(key, Const.DEFAULT_INDEX, User.class);
    }

    @Override
    public List<User> selectAddedFriendById(Long id) {
        return userMapper.selectAddedFriendById(id);
    }

    @Override
    public void loadCache() {
        List<User> users = selectList(null);
        for (User user : users) {
            String key = String.format(Const.USER_ID_USER, user.getId());
            redisService.setObject(key,user,Const.DEFAULT_INDEX);
        }
    }
}